package com.jingtai.core.template;

import com.jingtai.common.template.ResultMapInfo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class BaseController {


    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return Objects.requireNonNull(attrs).getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return Objects.requireNonNull(attrs).getResponse();
    }


    /**
     * 获取登陆IP
     *
     * @return
     */
    public static String getIpAddr() {
        HttpServletRequest request = getRequest();
        //处理代理访问获取不到真正的ip问题的
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            //获取代理中中的ip
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            //获取代理中中的ip

            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            //非代理的情况获取ip
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (StringUtils.isNotBlank(ip)) {
            String[] ips = ip.split(",");
            if (ips.length > 0) {
                ip = ips[0].trim();
            }
        }
        return ip;
    }

    protected Map<String, Object> returnResultMap(ResultMapInfo info) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", info.getCode());
        resultMap.put("message", info.getMessage());
        if (info.getCode() == 1) {
            resultMap.put("status", "SUCCESS");
        } else {
            resultMap.put("status", "FAIL");
        }
        resultMap.put("data", null);
        return resultMap;
    }

    protected Map<String, Object> returnResultMap(ResultMapInfo info, Object data) {
        Map<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("code", info.getCode());
        resultMap.put("data", data);
        resultMap.put("message", info.getMessage());
        if (info.getCode() == 1) {
            resultMap.put("status", "SUCCESS");
        } else {
            resultMap.put("status", "FAIL");
        }
        return resultMap;
    }
}
